from gmssl import sm3, func
   
def sm3_hash(data: bytes) -> bytes:
    return bytes.fromhex(sm3.sm3_hash(func.bytes_to_list(data)))
   
def calculate_z(user_id: bytes, public_key: bytes, sm2_params: dict) -> bytes:
    # 构造 Z = Hash(ENTL || ID || a || b || Gx || Gy || xA || yA)
    entl = len(user_id) * 8
    z_data = entl.to_bytes(2, byteorder='big') + user_id
    z_data += sm2_params['a'] + sm2_params['b']
    z_data += sm2_params['gx'] + sm2_params['gy']
    z_data += public_key
    z = sm3_hash(z_data)
    return z
   
def calculate_e(user_id: bytes, public_key: bytes, sm2_params: dict, message: bytes) -> bytes:
    z = calculate_z(user_id, public_key, sm2_params)
    c = z + message
    print("c value:", c.hex())
    e = sm3_hash(c)
    return e
   
def convert_public_key(x, y):
    # 将公钥坐标转换为字节格式
    x_bytes = b''.join(xi.to_bytes(4, byteorder='big') for xi in x)
    y_bytes = b''.join(yi.to_bytes(4, byteorder='big') for yi in y)
    return x_bytes + y_bytes
   
# SM2标准参数   
sm2_params = {
    'a': bytes.fromhex('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC'),
    'b': bytes.fromhex('28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93'),
    'gx': bytes.fromhex('32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7'),
    'gy': bytes.fromhex('BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0')   
}
   
# 用户ID   
user_id = b'1234567812345678'  # 示例用户ID
   
# 将公钥坐标转换为字节格式   
x_coords = [0x958E4164, 0x204F52F5, 0x4AE34032, 0x23EE5F42, 
            0xE01ED9EB, 0xECBEE98B, 0x04424CCE, 0x1E7AABD4]   
y_coords = [0xB3891DE9, 0xBFB2F38F, 0x4F252C38, 0x0590F206, 
            0xBDA63306, 0x626B646C, 0x76C1D7D9, 0x15D464F5]   
public_key = convert_public_key(x_coords, y_coords)
   
# 消息   
message = b'HELLO!'  # 示例消息
   
# 计算e值   
e_value = calculate_e(user_id, public_key, sm2_params, message)   
print("e value:", e_value.hex())
